﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Globalization;
using Medianamik.UI.Mediasend.Logic;
using Medianamik.Core;
using Medianamik.UI.Controls;
using Medianamik.UI.Mediasend.NodeTypes;
using Medianamik.Core.Sugar;
using NLog;

namespace Medianamik.UI.Mediasend.UserControls
{
    /// <summary>
    /// Sélection d'un noeud de type MediansendTemplate (Ou qui derive de MediasendTemplate)
    /// </summary>
    public partial class ucNodeSelection : MediasendUserControl
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            trvNodes.NeedChildren += trvNodes_NeedChildren;
            trvNodes.NeedSelfAndParents += trvNodes_NeedSelfAndParents;
            
            trvNodes.Skin = Skins.DEFAULT_SKIN;
            trvNodes.EnableEmbeddedSkins = Skins.DEFAULT_USE_EMBEDDED_SKIN;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            BindControls();
        }

        private void BindControls()
        {
            if (!IsPostBack)
            {
                SetControls();

                BindCultures();
            }
        }

        /// <summary>
        /// Construction du dropdown contenant l'ensemble des cultures.
        /// </summary>
        private void BindCultures()
        {
            var cultures = from medCulture in Page.EditionCultures
                           where medCulture.ContentManagementActive && medCulture.MedianamikActive
                           select new CultureInfo(medCulture.CultureName);

            rptLanguages.DataSource = cultures;
            rptLanguages.DataBind();
        }

        /// <summary>
        /// Permet de sélectionner la bonne langue dans le dropdown
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        protected string IsCultureSelected(object culture)
        {
            if (String.Equals(culture.ToString(), Page.CurrentEditionCulture.Name, StringComparison.OrdinalIgnoreCase))
                return "selected";
            
            return "";
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            string specializedScriptName = "OnClientNodeClickingHandlerFor" + trvNodes.ClientID;

            trvNodes.OnClientNodeClicking = specializedScriptName;

            //Le script doit exister (différent) pour chaque instance de ComboTree
            string specializedScript = String.Concat("function " + specializedScriptName + "(sender, args) {\n",
                    " var node = args.get_node();\n",
                    "if (node.get_category() == \"Disabled\") {\n",
                        "args.set_cancel(true);}\n",
                        "}\n");
            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), specializedScriptName, specializedScript, true);
        }

        /// <summary>
        /// Validation de la sélection d'au moins un gabarit.
        /// Attention, l'élément racine est sélectionné par défaut. Il faut
        /// donc s'assurer que l'élément racine n'a pas été sélectionné.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected void cvSelectTemplate_Validate(object sender, ServerValidateEventArgs args)
        {
            Guid selectedValue;
            args.IsValid = StringHelper.IsGuid(trvNodes.SelectedValue, out selectedValue) &&
                           !selectedValue.Equals(Configuration.Instance.Properties.BaseNodeTemplate.Value);
        }

        #region " TREEVIEW "
            void trvNodes_NeedChildren(object sender, Medianamik.UI.Controls.NeedChildrenEventArgs e)
            {
                try
                {

                    Guid g;
                    if (!StringHelper.IsGuid(e.ParentValue, out g))
                    {
                        g = Configuration.Instance.Properties.BaseNodeTemplate.Value;
                    }

                    var nodes = from node in NodeManager.GetChildNodes(g)
                                select
                                    (ITreeItem)
                                    (new TreeItem(node.DisplayName, node.ID.ToString(), null, node.NodeType.IconPath,
                                                  node.HasChildren,
                                                  node.NodeType.IsChildOf(MediasendTemplate.TypeId) || node.HasChildren,
                                                  node.Depth, node.NodeType.IsChildOf(MediasendTemplate.TypeId)));

                    e.ChildNodes.AddRange(nodes);
                }
                catch (Exception exc)
                {
                    var logger = LogManager.GetLogger("ActivityLogger");
                    logger.ErrorException("Error while getting templates", exc);

                    GlobalError = Translator.Translate("Medianamik_Mediasend", "ErrorPleaseContactSupport");
                }
            }

            void trvNodes_NeedSelfAndParents(object sender, NeedSelfAndParentsEventArgs e)
            {
                if (Configuration.Instance.Properties.BaseNodeTemplateNode != null)
                    e.Items.Add(new TreeItem(Configuration.Instance.Properties.BaseNodeTemplateNode.Name, Configuration.Instance.Properties.BaseNodeTemplateNode.ID.ToString(), null, null, true, true, int.MinValue, false));
            }
        #endregion

        
        #region IMediasendUserControl Members

            public override bool Save()
            {
                Guid selectedItemId;

                Data.Culture = Page.CurrentEditionCulture.Name;

                if (StringHelper.IsGuid(trvNodes.SelectedValue, out selectedItemId))
                {
                    Data.TargetTemplateId = selectedItemId;
                    if (Data.TargetTemplate.NodeType.IsChildOf(MediasendTemplate.TypeId))                    
                        return true;
                    else
                    {
                        Data.TargetTemplateId = null;
                        return false;
                    }
                }
                else
                    return false;
            }

            /// <summary>
            /// Changement de langue.
            /// </summary>
            public override void OnChangeCulture()
            {
                base.OnChangeCulture();
                trvNodes.Nodes.Clear();
                SetControls();
                BindCultures();
            }

            public override void SetControls()
            {
                if (Configuration.Instance.Properties.BaseNodeTemplate != null)
                    trvNodes.CurrentItemValue = Data.TargetTemplateId.HasValue ?
                                                Data.TargetTemplateId.ToString() :
                                                Configuration.Instance.Properties.BaseNodeTemplate.Value.ToString();
            }
        #endregion

    }
}